/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/


import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'dva';
import {
    Button,
    Row,
    Col,
    Input,
    message,
    Space,
    Dropdown,
    Menu,
    Form,
} from 'antd';
import {
    TablePaginationConfig
} from 'antd/es/table';
import { anyObj } from '@/types/components'
import {
    getSoaList,
    socpublish,
    changeList,
    postSocDel,
    postSocReback,
    serviceOffline,
    exportExcel,
    importExcelCheck,
} from '@/services/soa';
import {
    getSocList,
} from '@/services/soc';
// import IAutoPage from '@/components/soa/IAutoPage';
// 状态记录
import StatusRecords from './StatusRecords'
// 未发布服务
import UnpublishedService from './UnpublishedService'
// 已发布服务
import PublishedService from './PublishedService'
import SearchForm from './SearchForm'
import PageTabs from '@/components/common/PageTabs'
import CustomSpin from '@/components/common/CustomSpin';
import InportFile from './InportFile'
import BtnModal from './BtnModal';
import styles from './index.less';
import { useClickAway, useMount, useRequest, useUnmount } from 'ahooks';
import { downloadServiceFile } from '@/services/downloadURLFile'
import { DownOutlined } from '@ant-design/icons';
import useAuth from '@/utils/soa/useAuth';
import { getSeriesModelList } from '@/services/soa/sceneOfficial';
import ModalWin from '@/components/common/ModalWin';
import CarModel, { TextTitle } from './CarModel';
import { TaskModel, TaskUploadStatus } from '@/models/soaTask';
import { checkUploadStatus, getLocalStorage, initLocalStorage, setLocalStorage } from '@/utils/block';
import RequestSequence from '../../abilitymanagement/components/RequestSequence';
import { downloadArrayBufferFile, downloadBlobFile, getMd5, getToken } from '@/utils';
import { fingerprintFetch } from '@/utils/request';

const spanMarginLB = { margin: '0px 8px 8px 0px' }
const spanMarginL = { margin: '0px 8px 0px 0px' }
// const spanMarginRight = { marginRight: '10px' }
// const btnPopoverStyle = {
//     // color: "#fff",
//     height: 30,
//     cursor: 'pointer',
//     display: 'flex',
//     alignItems: 'center',
//     backgroundColor: 'transparent',
//     border: 'none',
// }
const downloadFile = (URL: string, file_path = '导出服务文件') => {
    const a = document.createElement('a');
    a.download = file_path;
    a.href = URL;
    a.target = '_blank';
    a.click();
    a.remove();
};

const useBrandName = (dispatch:any) => {
    // 品牌
    const [brandName, setBrandName] = React.useState<string>(localStorage.getItem('tenantCode') || '');

    useEffect(()=> {
        dispatch({
            type: 'vehicleInfoQuery/getData',
            payload: {
                url: '/common/vehicle/getcurrentbrand',
            },
            callback: (e: any) => {
                if (e?.data?.[0]?.brandName) {
                    setBrandName(e?.data?.[0]?.brandName)
                }
            },
        });
    }, []);

    return [brandName, setBrandName]
}
const { Item } = Form;

export const serviceManage: React.FC<any> = ({ dispatch, menu, task }) => {
    // 搜索组件ｒｅｆ
    const searchRef = React.useRef<any>()
    // 导入组件ｒｅｆ
    const importRef = React.useRef<any>()
    // 未发布搜索按钮
    const buttonRef = React.useRef<HTMLElement>(null) as React.MutableRefObject<HTMLElement>
    // 是否正在请求
    const [isRequest, setIsRequest] = React.useState(false)
    const [showPopover, setShowPopover] = React.useState(false)
    useClickAway(() => setShowPopover(false), buttonRef)
    // 显示ｔａｂ页面
    const [activeKey, setActiveKey] = React.useState<number | string>(1);
    // 导入弹窗步骤任务
    const [modalTask, setModalTask] = React.useState<string>('import');
    const [btnsText, setBtnsText] = React.useState<anyObj>({});
    // 修复退回-确认按钮置灰
    const [cDisabled, setCDisabled] = React.useState(true)
    // 未发布能力数量
    const [unpublishTotal, setUnpublishTotal] = React.useState(0);
    const [loading, setLoading] = React.useState(false);
    // 车型车系ｍａｐ
    const [carListMap, setListCarMap] = React.useState({});
    // 车机版本
    const [carSysVersion, setCarSysVersion] = React.useState<string>('');
    // 未发布服务列表 
    const [unpublishDataSource, setUnpublishDataSource] = React.useState<any[]>([]);
    // 已发布服务列表 
    const [publishedDataSource, setPublishedDataSource] = React.useState<any[]>([]);
    // 导入弹框
    const [isModalVisible, setIsModalVisible] = React.useState<boolean>(false);
    // 退回弹窗
    const [returnShow, setReturnShow] = React.useState(false);
    // 退回原因
    const [textAreaReason, setTextAreaReason] = React.useState<string>('');
    // 导入校验加载
    const [importBtnLoading, setImportBtnLoading] = React.useState<boolean>(false);
    // 导入校验弹窗
    const [checkShow, setCheckShow] = React.useState(false);
    // 导入表单提交数据
    const [formData, setFormData] = React.useState<any>({});
    // 按钮权限map
    const hasAuth = {
        'import': useAuth('/soaManage/serviceManage/serviceManage_doImport', menu),
        'unPublishExport': useAuth('/soaManage/serviceManage/serviceManage_doUnPublishExport', menu),
        'publishExport': useAuth('/soaManage/serviceManage/serviceManage_doPublishExport', menu),
        'back': useAuth('/soaManage/serviceManage/serviceManage_doBack', menu),
        'publish': useAuth('/soaManage/serviceManage/serviceManage_doPublish', menu),
        'cleanUp': useAuth('/soaManage/serviceManage/serviceManage_doCleanUp', menu),
        'takeDown': useAuth('/soaManage/serviceManage/serviceManage_doTakeDown', menu),
    }
    const [brandName] = useBrandName(dispatch);
    // 获取车系车型
    const seriesModelList = useRequest(getSeriesModelList);
    const [form] = Form.useForm()
    // const [uploadStatus, setUploadStatus] = useState<TaskUploadStatus>('pending');
    // const { uploadStatus } = task;
    // console.log("🚀 ~ file: index.tsx ~ line 165 ~ uploadStatus", uploadStatus)

    // 未发布服务分页
    const [unpublishPagination, setUnpublishedPagination] = React.useState<TablePaginationConfig>({
        current: 1,
        pageSize: 10,
        total: 0,
        onChange: (page: number, pageSize: number) => {
            setUnpublishedPagination({
                ...unpublishPagination,
                // current: page, 
                pageSize
            })
            searchRef?.current?.getTableList(page, pageSize)
        },
    });
    // 已发布服务分页
    const [publishedPagination, setPublishedPagination] = React.useState<TablePaginationConfig>({
        current: 1,
        pageSize: 10,
        total: 0,
        onChange: (page: number, pageSize: number) => {
            setPublishedPagination({
                ...publishedPagination,
                // current: page, 
                pageSize
            })
            searchRef?.current?.getTableList(page, pageSize)
        },
    });
    // 发布服务弹窗
    const publishWinService = React.useCallback(
        () => {
            setBtnsText({
                titleBtn: <TextTitle text='发布' />,
                content: <CarModel form={form} seriesModelList={seriesModelList} />
            })
            // setModalTask('publishModalTask')
            setModalTask('publishChangeWin')
            setReturnShow(true);
        }, [seriesModelList])
    // 未发布车型车系版本服务清空
    const postWinSocDel = React.useCallback(() => {
        setBtnsText({
            titleBtn: <TextTitle text='清空' />,
            content: <CarModel form={form} seriesModelList={seriesModelList} />
        })
        setModalTask('serviceSocDelTask')
        setReturnShow(true);
    }, [seriesModelList])
    
    // 已发布服务下架弹窗
    const serviceWinOffline = React.useCallback(() => {
        const sfCurrent = searchRef?.current || {}
        const formData = sfCurrent?.searchForm?.getFieldsValue() || {}
        const smCode = sfCurrent?.carMap[formData?.smCode[0]] || {}
        if (!smCode || !smCode?.seriesName) {
            message.warning('车型车系错误！')
            return
        }
        setBtnsText({
            checkResText: [
                `${smCode.seriesName}/${smCode?.models[formData?.smCode[1]]?.modelName}车型${formData.carSysVersion || carSysVersion}版本将要下架`
            ]
        })
        setModalTask('serviceOfflineDelTask')
        setReturnShow(true);
    }, [carSysVersion])
    // 获取服务列表
    const getList = React.useCallback(async (curpagination = 1, pageSize = null, dataCar = [], dataSoc = '', akNuber = activeKey) => {
        if (akNuber == 1 || !searchRef?.current?.searchForm?.getFieldsValue) {
            // 状态记录ｔａｂ
            return
        }
        const formData: any = searchRef?.current?.searchForm?.getFieldsValue() || { smCode: [] }
        // console.log(formData, 'formData')
        // 查询的时候如果没有选中soc则需要清空列表数据
        if (!formData.carSysVersion) {
            setPublishedDataSource([]);
            setUnpublishDataSource([]);
            return
        }
        setLoading(true);
        // console.log(dataCar, 'dataCar')
        if (!dataCar[0] && !formData?.smCode[0]) {
            if (akNuber == 2) {
                // 未发布服务
                setUnpublishDataSource([]);
                setUnpublishedPagination((state) => {
                    return {
                        ...state,
                        total: 0,
                        pageSize: 10,
                        current: 1,
                    };
                });
            } else {
                // 已发布服务
                setPublishedDataSource([]);
                setPublishedPagination((state) => {
                    return {
                        ...state,
                        total: 0,
                        pageSize: 10,
                        current: 1,
                    };
                });
            }
            setTimeout(() => setLoading(false), 360)
            return
        }
        const sedData = {
            current: curpagination || (akNuber == 2 ? unpublishPagination.current : publishedPagination.current),
            pagesize: pageSize || (akNuber == 2 ? unpublishPagination.pageSize : publishedPagination.pageSize),
            status: akNuber == 2 ? 0 : 1,
            sCode: dataCar[0] || formData?.smCode[0],
            mCode: dataCar[1] || formData?.smCode[1],
            socVersion: dataSoc || formData?.carSysVersion,
            sName: formData?.servicesName
        };
        setLoading(true);
        const resSoa = await getSoaList(sedData);
        setLoading(false)
        if (resSoa?.statusCode == '0') {
            if (akNuber == 2) {
                // 未发布服务
                setUnpublishDataSource(resSoa?.data?.dataList || []);
                setUnpublishedPagination((state: any) => {
                    return {
                        ...state,
                        total: resSoa?.data?.pageCount || 0,
                        pageSize: resSoa?.data?.pagesize || sedData?.pagesize || 10,
                        current: resSoa?.data?.pageNo || sedData?.current || 1,
                    };
                });
            } else {
                // 已发布服务
                setPublishedDataSource(resSoa?.data?.dataList || []);
                setPublishedPagination((state: any) => {
                    return {
                        ...state,
                        total: resSoa?.data?.pageCount || 0,
                        pageSize: resSoa?.data?.pagesize || sedData?.pagesize || 10,
                        current: resSoa?.data?.pageNo || sedData?.current || 1
                    };
                });
            }
        }
    },
        [unpublishPagination, publishedPagination, activeKey])
    // 导出服务下载
    const getExportExcel = React.useCallback(
        async () => {
            const sfCurrent = searchRef?.current || {};
            const fd = sfCurrent.searchForm?.getFieldsValue() || {};
            const data = {
              sCode: fd?.smCode[0],
              mCode: fd?.smCode[1],
              socVersion: fd?.carSysVersion,
            };
            if (!fd.smCode) {
              message.warning('车型车系错误！');
              return;
            }
            setLoading(true);
            const paramsStr = Object.keys(data)
              .map(key => `${key}=${data[key]}`)
              .join('&');
            const md5 = getMd5(paramsStr);
            const str = `${window.g.url}/api/ms-soa-service/v1/admin/carmodel/soc/exportExcel?${paramsStr}`;
            const newOptions = {};
            newOptions.headers = { OptAuthorization: getToken(), Shasign: md5 };

            const smCode = sfCurrent?.carMap[fd?.smCode[0]] || {};
            const seriesName = smCode?.seriesName || '导出';
            const modelName = smCode?.models[fd?.smCode[1]]?.modelName || '文件';
            let res: Response | null = null;
            await fingerprintFetch(str, newOptions)
              .then(response => {
                res = response;
                if (response.status === 200) {
                  return response;
                } else {
                  throw response;
                }
              })
              .catch(() => message.error('导出失败，请稍后在试!'));
            // 兼容新旧导出
            Promise.allSettled([res.clone().json(), res.clone().blob()]).then(resList => {
              if (resList[0].status === 'fulfilled') {
                if(resList[0].value?.statusCode == '0'){
                    const URL = resList[0].value?.data?.fileAddr;
                    downloadFile(
                      URL,
                      `${seriesName}/${modelName} 车型${fd?.carSysVersion || carSysVersion}服务.xlsx`,
                    );
                }else{
                    message.error(resList[0].value?.statusMessage)
                }
              } else if (resList[1].status === 'fulfilled') {
                downloadBlobFile(
                  resList[1].value,
                  `${seriesName}/${modelName} 车型${fd?.carSysVersion || carSysVersion}服务.xlsx`,
                );
              }
            });
            // await exportExcel(data).then((res: any) => {
            //     if (res?.statusCode == '0') {
            //         const smCode = sfCurrent?.carMap[fd?.smCode[0]] || {}
            //         const URL = res?.data?.fileAddr;
            //         const seriesName = smCode?.seriesName || '导出';
            //         const modelName = smCode?.models[fd?.smCode[1]]?.modelName || '文件';
            //         downloadFile(URL, `${seriesName}/${modelName} 车型${fd?.carSysVersion || carSysVersion}服务.xlsx`);
            //     }
            // });
            setLoading(false)
        },
        []
    )
    // 发布获取变更列表
    const getChangeList = React.useCallback(
        async () => {
            const values = form.getFieldsValue();
            if (!values.carSeries?.length) {
                // 没有选择车系
                message.warning('请选择车系!');
                return
            }
            if (!values.carModels?.length) {
                // 没有选择车型
                message.warning('请选择车型!');
                return
            }
            const data = {
                sCode: values.carSeries[0],
                mCode: values.carModels.join(','),
                // socVersion: '',
            };
            setLoading(true);
            const resCheck = await changeList(data);
            setLoading(false);
            if (resCheck?.statusCode == '0') {
                publishService()
            } else {
                message.error('服务发布失败！')
            }
            setReturnShow(false)
        },
        []
    )
    // 发布发布服务
    const publishService = React.useCallback(
        async () => {
            const values = form.getFieldsValue();
            if (!values.carSeries?.length) {
                // 没有选择车系
                message.warning('请选择车系!');
                return
            }
            if (!values.carModels?.length) {
                // 没有选择车型
                message.warning('请选择车型!');
                return
            }
            const data = {
                sCode: values.carSeries[0],
                mCode: values.carModels.join(','),
                // socVersion: '',
            };
            setLoading(true)
            const res = await socpublish(data);
            setLoading(false)
            if (res?.statusCode == '0') {
                setActiveKey(3)
                // 发布服务切换到已发布服务ｔａｂ，手动设置车型车系版本号搜索
                searchRef?.current?.getCarType(3, false, false)
                // searchRef?.current?.selectedModel(
                //     fd?.carSysVersion,
                //     fd?.smCode,
                //     null, 3,
                // )
                // searchRef?.current?.getTableList(
                //     1, 10,
                //     fd?.smCode,
                //     fd?.carSysVersion,
                //     3
                // )
                searchRef?.current?.getEditionList([values.carSeries[0], values.carModels[0]], true, true);
                message.success('发布成功');
            } else {
                message.warning('服务发布失败!');
            }
        }, [])
    // 服务下架请求
    const offlineService = React.useCallback(
        async () => {
            const fd = searchRef?.current?.searchForm?.getFieldsValue() || {}
            const data = {
                sCode: fd?.smCode[0],
                mCode: fd?.smCode[1],
                socVersion: fd?.carSysVersion,
                userId: 'test',
            };
            setLoading(true)
            const resSocDel = await serviceOffline(data);
            setLoading(false)
            if (resSocDel?.statusCode == '0') {
                message.success(`下架成功`);
                // 需要切换到未发布页面
                // 设置activeKey给搜索表单处理
                setActiveKey(2);
                setUnpublishDataSource([]);
                setPublishedDataSource([]);
                // 下架服务后重新获取未发布车型车系搜索
                searchRef?.current?.getCarType(2, false, true)
                // searchRef?.current?.getTableList()
            } else {
                message.error(resSocDel?.statusMessage);
            }
        }, [])
    // 清空未发布服务
    const socDelService = React.useCallback(
        async () => {
            const values = form.getFieldsValue();
            if (!values.carSeries?.length) {
                // 没有选择车系
                message.warning('请选择车系!');
                return
            }
            if (!values.carModels?.length) {
                // 没有选择车型
                message.warning('请选择车型!');
                return
            }
            const data = {
                sCode: values.carSeries[0],
                mCode: values.carModels.join(','),
                // socVersion: '',
            };
            setLoading(true)
            const resSocDel = await postSocDel(data);
            setLoading(false)
            if (resSocDel?.statusCode == '0') {
                setActiveKey(2)
                message.success(
                    `已清空`
                );
                // 清空服务后重新获取未发布车型车系搜索
                searchRef?.current?.getCarType(2, false, true);
            } else {
                message.error('服务清空失败!');
            }
            setReturnShow(false)
        }, [form])
    // 服务版本退回
    const serviceSocReback = React.useCallback(
        async (textReason: string) => {
            const values = form.getFieldsValue();
            if (!values.carSeries?.length) {
                // 没有选择车系
                message.warning('请选择车系!');
                return
            }
            if (!values.carModels?.length) {
                // 没有选择车型
                message.warning('请选择车型!');
                return
            }
            if (!values.reason) {
                // 没有选择车型
                message.warning('请填写原因!');
                return
            }
            const data = {
                sCode: values.carSeries[0],
                mCode: values.carModels.join(','),
                // socVersion: '',
                reason: values.reason,
                userId: 'test'
            };
            setLoading(true)
            const resSocDel = await postSocReback(data);
            setLoading(false)
            setTextAreaReason('')
            if (resSocDel?.statusCode == '0') {
                message.success(
                    `已退回`
                );
                setActiveKey(2);
                // 退回服务后重新获取未发布车型车系搜索
                searchRef?.current?.getCarType(2, false, true)
            } else {
                message.error('服务退回失败!');
            }
        }, [])
    // 导入服务
    const importService = React.useCallback(
        (fd: any = null, taskData: any = null) => {
            setCheckShow(false)
            setImportBtnLoading(false)
            // const [sCode, mCode] = taskData?.selectedCarVal || []
            // setLoading(true)
            dispatch({
                type: 'serviceModel/postImportExcel',
                payload: fd,
            }).then((resImport: any) => {
                if (resImport?.statusCode == '0') {
                    setLocalStorage('uploadStatus', 'completed')
                    setCheckShow(false)
                    // message.success('导入完成！')
                    // setActiveKey(2);
                    // const srCurrent = searchRef?.current || {}
                    // // 导入服务后重新获取未发布车型车系，手动设置车型车系版本号搜索
                    // searchRef?.current?.getCarType(2, false, true)
                    // srCurrent?.selectedModel(
                    //     taskData?.importCarModeVersion || srCurrent?.carMap[sCode]?.models[mCode]?.socVersion,
                    //     taskData?.selectedCarVal
                    // )
                    // importRef?.current?.resetFormData()
                    // 修复导入完成重复查询列表
                    // srCurrent?.getTableList()
                }
                else if (resImport?.statusCode == '40060409') {
                    // TODO 当前正在导入，请稍后再试！
                    setBtnsText({
                        cancel: false,
                        checkResText: [resImport?.statusMessage]
                    })
                    setModalTask('cancelImport')
                    setCheckShow(true)
                }
                else if (resImport?.statusCode == '40060415') {
                    // 服务文件格式错误，请检查文件!  (确认按钮)    前端按照后台返回的msg显示
                    setBtnsText({
                        cancel: false,
                        checkResText: [resImport?.statusMessage]
                    })
                    setModalTask('cancelImport')
                    setCheckShow(true)
                } else {
                    // message.error('导入失败！')
                }
                setImportBtnLoading(false)
                // setLoading(false)
            })
        }, [])
    // 导入功能-校验
    const afterCheckImportExcel = React.useCallback(
        (taskData: anyObj = {}) => {
            console.log("🚀 ~ file: index.tsx ~ line 550 ~ taskData", taskData)
            setIsModalVisible(false)
            const fd = new FormData();
            const [sCode, mCode] = taskData?.selectedCarVal || []
            fd.append('file', taskData?.socFileList[0]);
            fd.append('sCode', sCode);
            fd.append('mCode', mCode);
            fd.append('socVersion', taskData?.importCarModeVersion);
            // fd.append('brand', 'brand1');
            fd.append('brand', '1');
            // setLoading(true)
            setCheckShow(false)
            setImportBtnLoading(false)
            if (isRequest) {
                return
            }
            setIsRequest(true);
            if (dispatch) {
                dispatch({
                    type: 'serviceModel/getImportExcelCheck',
                    payload: fd,
                }).then((resCheck: any) => {
                    // setLoading(false)
                    setIsRequest(false);
                    if (resCheck?.statusCode == '0') {
                        // 文件检查通过=>上传文件
                        // fix：根据yapi上接口参数，无分页结构的不需要返回dataList，所以需要删掉
                        if (resCheck?.data?.length > 0) {
                            // * 4、导入的服务相对前一版本接口有变化 —> 服务接口有更新，请发布后及时更新相关能力。如下：
                            // * 服务接口：setAirCdAcMode 接口ID：0x0001 接口描述：设置打开/关闭A/C
                            // * 服务接口：setAqsIonizer 接口ID：0x0002 接口描述：设置空调自动循环空气净化

                            if (getLocalStorage('isConfirm', false)) {
                                importService(
                                    fd,
                                    taskData,
                                )
                                return
                            }
                            setIsModalVisible(false)
                            setCheckShow(true)
                            setLocalStorage('isConfirm', true)
                            setBtnsText({
                                checkResText: ['服务接口有更新，请发布后及时更新相关能力。差分内容请到未发布服务列表查看。']
                            })
                            setFormData({
                                fd,
                                taskData,
                            })
                            setModalTask('importComplete')
                        } else {
                            //  6、导入完成！ —> 设置搜索条件车型车系为导入服务所选车型车系 —> 查询新服务列表
                            importService(
                                fd,
                                taskData,
                            )
                        }
                    }
                    // 该部分代码多余,如果是文件格式错误则走通用拦截提示
                    //  else if (resCheck?.statusCode == '500') {
                    // 文件校验不通过
                    // 1、文件格式检查，不符合格式 —> 服务格式错误，请检查文件！
                    // message.warning('服务格式错误，请检查文件！')
                    // importRef?.current?.resetFormData()
                    // }
                    // fix：更新服务305对应的code
                    else if (resCheck?.statusCode == '40060305') {
                        // * 3、服务器中已有相同已发布版本 —> 相同版本已发布，将取消导入，请更新后再导入。
                        setBtnsText({
                            cancel: false,
                            checkResText: ['相同版本已发布，将取消导入，请更新后再导入。']
                        })
                        setModalTask('cancelImport')
                        setCheckShow(true)
                    }
                    else if (resCheck?.statusCode == '40060415') {
                        // 服务文件格式错误，请检查文件!  (确认按钮)    前端按照后台返回的msg显示
                        setBtnsText({
                            cancel: false,
                            checkResText: [resCheck?.statusMessage]
                        })
                        setModalTask('cancelImport')
                        setCheckShow(true)
                    }
                    else if (resCheck?.statusCode == '40060500') {
                        // 2、服务器中已有未发布版本 —> 已有未发布版本，是否替换更新？
                        if (getLocalStorage('isConfirmUpdate', false)) {
                            importService(
                                fd,
                                taskData,
                                )
                                return
                            }
                        setIsModalVisible(false)
                        setCheckShow(true)
                        setLocalStorage('isConfirmUpdate', true)
                            // 服务器中已有未发布版本
                        setBtnsText({
                            confirm: '更新',
                            checkResText: [resCheck?.statusMessage]
                        })
                        setFormData({
                            fd,
                            taskData,
                        })
                        setModalTask('importComplete')
                    }
                    else if (resCheck?.statusCode == '40060409') {
                        // TODO 当前正在导入，请稍后再试！
                        setBtnsText({
                            cancel: false,
                            checkResText: [resCheck?.statusMessage]
                        })
                        setModalTask('cancelImport')
                        setCheckShow(true)
                    } else {
                        // message.error(res?.error?.message)
                        // message.error('服务错误，请稍再试！')
                        console.error("🚀 ~ file: index.tsx ~ line 602 ~ resCheck", resCheck)
                        // importRef?.current?.resetFormData()
                    }

                });
            }
        }, [])
    // 导入弹窗提交
    const importWinSubmit = React.useMemo(
        () =>
            async (taskData: any, isAuto = false) => {
                console.log("🚀 ~ file: index.tsx ~ line 628 ~ taskData", taskData)
                
                // 导入任务弹窗
                // console.log('弹窗提交数据', modalTask, taskData)
                /***
                 * 导入服务前请求了 api/servicemgmt/v1/admin/carmodel/soc/list
                 * 然后请求 api/servicemgmt/v1/admin/service/importExcelCheck
                 * 最后请求 servicemgmt/v1/admin/service/importExcel
                 * **/
                /**** 导入检验接口接口
                * 2、服务器中已有未发布版本 —> 已有未发布版本，是否替换更新？
                * 1、文件格式检查，不符合格式 —> 服务格式错误，请检查文件！
                * 3、服务器中已有相同已发布版本 —> 相同版本已发布，将取消导入，请更新后再导入。
                * 4、导入的服务相对前一版本接口有变化 —> 服务接口有更新，请发布后及时更新相关能力。如下：
                * 服务接口：setAirCdAcMode 接口ID：0x0001 接口描述：设置打开/关闭A/C
                * 服务接口：setAqsIonizer 接口ID：0x0002 接口描述：设置空调自动循环空气净化
                * 5、文件检查通过 —> 导入完成！
                * 2弹窗点更新按钮、4弹窗点确认按钮 —> 导入完成！
                * 6、导入完成！ —> 设置搜索条件车型车系为导入服务所选车型车系 —> 查询新服务列表
                *****/
                if (modalTask == 'importModalTask') {

                    if (!isAuto) { // 自动执行任务
                        // 生成请求列表
                        const [sCode, mCode] = taskData.selectedCarVal;
                        const sfCurrent = searchRef?.current || {}
                        const smCode = sfCurrent?.carMap[sCode] || {}
                        const seriesName = smCode?.seriesName;
                        const tasks: TaskModel['state']['tasks'] = [];
                        const reqList = mCode.split(',').map((val, index) => {
                            const modelName = smCode?.models[val]?.modelName;
                            tasks.push({
                                id: (index + 1).toString(),
                                brandCode: brandName as string,
                                brandName: brandName as string,
                                seriesCode: sCode,
                                seriesName: seriesName,
                                modelCode: val,
                                modelName: modelName,
                                version: taskData?.importCarModeVersion || '',
                                status: 1
                            })
                            return {
                                ...taskData,
                                selectedCarVal: [sCode, val],
                                id: (index + 1).toString(),
                            }
                        })
                        // 添加任务列表
                        dispatch({
                            type: 'task/addTasks',
                            payload: tasks
                        })
    
                        // 开始任务
                        let index = 0;
                        setLoading(true);
                        for (const req of reqList) {
                            setLocalStorage('uploadStatus', 'pending')
                            dispatch({
                                type: 'task/updateTaskStatus',
                                payload: {
                                    taskId: req.id,
                                    newStatus: 2, //导入中
                                    disabled: true
                                }
                            })
                            // 自动任务
                            importWinSubmit(req, true)
                            // 查询执行状态结果
                            const upStatus = await checkUploadStatus()
    
                            if (upStatus === 'completed') { // 成功
                                dispatch({
                                    type: 'task/updateTaskStatus',
                                    payload: {
                                        taskId: req.id,
                                        newStatus: 3, //导入中
                                        disabled: index === reqList.length ? false : true
                                    }
                                })
                            } else if(upStatus === 'failed') { // 失败
                                // // 处理 所有未成功的 任务 状态变成终止
                                // dispatch({
                                //     type: 'task/updateAllTaskStatus'
                                // })
                                break;
                            }
                            index ++
                        }
                        dispatch({
                            type: 'task/updateAllTaskStatus'
                        })
                        setLoading(false);
                        setActiveKey(2);
                        const srCurrent = searchRef?.current || {}
                        // 导入服务后重新获取未发布车型车系，手动设置车型车系版本号搜索
                        searchRef?.current?.getCarType(2, false, true)
                        reqList[0]
                        srCurrent?.selectedModel(
                            reqList[0]?.importCarModeVersion || srCurrent?.carMap[sCode]?.models[mCode]?.socVersion,
                            reqList[0]?.selectedCarVal
                        )
                        importRef?.current?.resetFormData()
                        return
    
                    }
                    
                    // 导入弹窗提交＝＞校验
                    setImportBtnLoading(true)
                    // setLoading(true);
                    // const resSoc = await getSocList({
                    //     mCode: taskData?.selectedCarVal[1],
                    //     sCode: taskData?.selectedCarVal[0],
                    //     current: 1,
                    //     pagesize: 10,
                    //     status: 0,
                    //     // brand: 'brand1'
                    //     brand: '1'
                    // });
                    // setLoading(false);
                    // if (resSoc?.data?.dataList?.length > 0) {
                    //     // 2、服务器中已有未发布版本 —> 已有未发布版本，是否替换更新？
                    //     setIsModalVisible(false)
                    //     setCheckShow(true)
                    //     // 服务器中已有未发布版本
                    //     setBtnsText({
                    //         confirm: '更新',
                    //         checkResText: ['已有未发布版本，是否替换更新？']
                    //     })
                    //     setModalTask('replaceUpdate')
                    // } else {
                        // 导入服务校验
                        afterCheckImportExcel(taskData)
                    // }
                } else {
                    switch (modalTask) {
                        // 替换更新弹窗提交
                        case 'replaceUpdate':
                            // 导入服务校验
                            afterCheckImportExcel(taskData)
                            break;
                        // 取消导入弹窗提交
                        case 'cancelImport':
                            setLocalStorage('uploadStatus', 'failed')

                            setCheckShow(false)
                            setImportBtnLoading(false)
                            // importRef?.current?.resetFormData()
                            break;
                        // * 4、导入的服务相对前一版本接口有变化 —> 服务接口有更新，请发布后及时更新相关能力。如下：
                        // * 服务接口：setAirCdAcMode 接口ID：0x0001 接口描述：设置打开/关闭A/C
                        // * 服务接口：setAqsIonizer 接口ID：0x0002 接口描述：设置空调自动循环空气净化
                        case 'importComplete':
                            importService(
                                formData.fd,
                                formData.taskData
                            )
                            break;
                        default: break
                    }
                }
            }
        , [modalTask, formData])
    // 提示弹窗提交
    const noticeWinSubmit = React.useMemo(
        () =>
            () => {
                // console.log('弹窗提交数据', modalTask, taskData)
                switch (modalTask) {
                    // 退回提交提示弹窗任务提交
                    case 'returnModal':
                        if (textAreaReason.length >= 5) {
                            serviceSocReback(textAreaReason)
                        } else {
                            message.warning('退回原因最少五个字符！')
                            return
                        }
                        break
                    // 发布任务提示弹窗弹窗任务提交
                    case 'publishModalTask':
                        publishService()
                        break
                    // 未发布服务清空提示弹窗任务提交
                    case 'serviceSocDelTask':
                        socDelService()
                        return
                    // 服务下架提示弹窗任务提交
                    case 'serviceOfflineDelTask':
                        offlineService()
                        break
                    // 服务发布弹窗提示
                    case 'publishChangeWin':
                        // getChangeList()
                        publishService()
                        break;
                    case 'exportServiceTask':
                        getExportExcel()
                        break;
                    default:
                        break;
                }
                setReturnShow(false)
            }
        , [modalTask, textAreaReason])
    // 退回输入
    const returnInput = React.useMemo(
        () => (<>
            <CarModel form={form} seriesModelList={seriesModelList} >
                <Item
                    label="请填写"
                    name="reason"
                    rules={[
                        {
                            required: true,
                            message: '退回信息为必填内容，请选择！',
                        },
                    ]}
                >
                    <Input.TextArea rows={4} maxLength={200} placeholder="请输入最少五个字符" onChange={
                        (ev: any) =>
                            {
                                setTextAreaReason(ev.target.value)
                                form.setFieldsValue({
                                    reason: ev.target.value
                                })
                            }
                    } />
                </Item>
            </CarModel>
            </>
        ), [seriesModelList])
    // 导出服务
    const handleExportService = React.useCallback(
        () => {
            setShowPopover(false)
            const sfCurrent = searchRef?.current || {}
            const formData = sfCurrent?.searchForm?.getFieldsValue() || {}
            const smCode = sfCurrent?.carMap[formData?.smCode[0]] || {}
            if (!smCode || !smCode?.seriesName) {
                message.warning('车型车系错误！')
                return
            }
            if (!(formData?.carSysVersion || carSysVersion)) {
                message.warning('服务矩阵版本号错误！')
                return
            }
            setBtnsText({
                checkResText: [
                    `将下载${smCode?.seriesName}/${smCode?.models[formData?.smCode[1]]?.modelName}服务矩阵版本号${formData?.carSysVersion || carSysVersion}的服务，`,
                    `请确认是否下载`
                ]
            })
            setModalTask('exportServiceTask')
            setReturnShow(true);
        },
        []
    )
    // 导出模板
    const handleExportTemplate = React.useCallback(
        async () => {
            setShowPopover(false);
            setLoading(true)
            downloadServiceFile()
            setLoading(false)
        },
        []
    )

    // 获取查询按钮禁用状态
    const handleGetSearchDisabeled = React.useCallback(()=> {
        const values = searchRef.current?.searchForm?.getFieldsValue();
        // fix: 获取车型 服务矩阵版本号 都有值才不禁用
        if (values?.carSysVersion && values?.smCode?.length === 2) {
            return false;
        }
        return true;
    }, [searchRef.current]);

    const domPopover = React.useMemo(
        () =>
            <Dropdown overlay={
                <Menu>
                    {
                        carSysVersion && unpublishDataSource.length ?
                            <Menu.Item key={1} onClick={handleExportService}>导出服务</Menu.Item> : null
                    }
                    <Menu.Item key={2} onClick={handleExportTemplate}>导出模板</Menu.Item>
                </Menu>
            }>
                <Button type={'primary'} size={'small'} style={{ ...spanMarginLB, display: hasAuth.unPublishExport ? 'inline-block' : 'none' }} >
                    <Space>导出</Space>
                    <DownOutlined />
                </Button>
            </Dropdown>
        // <Popover
        //     placement="bottomLeft"
        //     overlayInnerStyle={{ borderRadius: '6px' }}
        //     trigger="click"
        //     zIndex={999}
        //     visible={showPopover}
        //     content={
        //         <div >
        //             {
        //                 carSysVersion && unpublishDataSource.length ?
        //                     <Button style={{ ...btnPopoverStyle, marginBottom: '12px' }}
        //                         onClick={() => handleExportService()} >
        //                         导出服务
        //                     </Button> : null
        //             }
        //             <Button style={btnPopoverStyle}
        //                 onClick={() => handleExportTemplate()} >
        //                 导出模板
        //             </Button>
        //         </div>
        //     }
        // >
        //     <Button
        //         ref={buttonRef}
        //         type={carSysVersion ? 'primary' : 'default'}
        //         // disabled={carSysVersion ? false : true}
        //         size="small"
        //         onClick={() => setShowPopover(!showPopover)}
        //         style={{
        //             ...spanMarginLB,
        //         }} >
        //         <Space>导出</Space>
        //         <DownOutlined />
        //     </Button>
        // </Popover>
        ,
        [showPopover, carSysVersion, unpublishDataSource.length, hasAuth.unPublishExport]
    )
    // 未发布服务搜索按钮
    const unpublishSearch = React.useMemo(
        () => (<div>
            <div style={{ display: 'inline-block' }}>
                <div>
                    <Button type='primary'
                        size="small" style={spanMarginLB}
                        disabled={handleGetSearchDisabeled()}
                        onClick={() => getList()}>查询</Button>
                    {hasAuth.import && <Button type='primary'
                        size="small" style={spanMarginLB}
                        onClick={() => {
                            setModalTask('importModalTask')
                            setIsModalVisible(true)
                        }}>导入</Button>}
                    {domPopover}
                </div>
                <div style={{ textAlign: 'left' }}>
                    {hasAuth.back && <Button
                        //  type='primary'
                        disabled={
                            !(
                                carSysVersion &&
                                unpublishDataSource.length &&
                                !unpublishDataSource?.some(item => item.status == 2)
                            )
                        }
                        size="small" style={spanMarginL}
                        onClick={() => {
                            setBtnsText({
                                titleBtn: <TextTitle text='退回' />,
                                content: returnInput,
                            })
                            setCDisabled(true)
                            setModalTask('returnModal')
                            setReturnShow(true);
                        }}>退回</Button>}
                    {hasAuth.publish && <Button
                        // type='primary' 
                        disabled={!carSysVersion}
                        size="small" style={spanMarginL}
                        onClick={() => publishWinService()}>发布</Button>}
                    {hasAuth.cleanUp && <Button
                        disabled={!carSysVersion}
                        size="small" style={spanMarginL}
                        onClick={
                            () => postWinSocDel()
                        }>清空</Button>}
                </div>
            </div>
        </div>),
        [carSysVersion, domPopover, unpublishDataSource, getList])
    // 已发布搜索按钮
    const publichedSearch = React.useMemo(
        () => (<>
            <Button type='primary'
                size="small" style={spanMarginL}
                disabled={handleGetSearchDisabeled()}
                onClick={() => getList()}>查询</Button>
            {hasAuth.publishExport && <Button
                // type='primary' 
                disabled={!carSysVersion}
                size="small" style={spanMarginL}
                onClick={() => handleExportService()}>导出</Button>}
            {hasAuth.takeDown && <Button
                // type='primary' 
                disabled={!carSysVersion}
                size="small" style={spanMarginL}
                onClick={() => serviceWinOffline()}>下架</Button>}
        </>), [carSysVersion, getList])
    const domPageTabs = React.useMemo(
        () =>
            <PageTabs
                tabPaneList={['状态记录', '未发布服务', '已发布服务']}
                activeKey={activeKey}
                setActiveKey={
                    (ak: number) => {
                        // ｔａｂ切换标记
                        if (ak != 1) {
                            searchRef?.current?.searchForm?.setFieldsValue({
                                ...searchRef?.current?.searchForm?.getFieldsValue(),
                                servicesName: '',
                            })
                        }
                        // fix:修复从已发布服务切换到状态记录再切换回已发布服务时列表仍然显示数据问题
                        if (ak == 3) {
                            setPublishedDataSource([]);
                        }
                        setActiveKey(ak)
                        searchRef?.current?.getCarType(ak, ak == 3 ? true : false, true)
                    }
                }
                unpublishTotal={unpublishTotal || 0}
            ></PageTabs>,
        [activeKey, unpublishTotal]
    )
    {/* ｆｏｒｍ筛选搜索表单 */ }
    const domSearchForm = React.useMemo(
        () => <SearchForm
            // key={activeKey}
            ref={searchRef}
            setLoading={setLoading}
            allOptionNum={activeKey == 2}
            allOptionDot={activeKey == 2}
            loadingActive={activeKey != 1}
            carSysVersion={carSysVersion}
            emitCarSysVersion={setCarSysVersion}
            status={activeKey}
            dispatch={dispatch}
            unpublishTotal={unpublishTotal}
            setUnpublishTotal={setUnpublishTotal}
            setPublishedDataSource={() => setPublishedDataSource([])}
            setCarMap={setListCarMap}
            carMap={carListMap}
            getTableList={getList}
            buttoms={
                activeKey == 2 ? unpublishSearch : publichedSearch
            } ></SearchForm>,
        [activeKey, carSysVersion, carListMap, unpublishTotal, domPopover, unpublishDataSource, getList]
    )
    {/* 状态记录 */ }
    const domStatusRecords = React.useMemo(
        () =>
            <StatusRecords
                dispatch={dispatch}
                setLoading={setLoading}
                setActiveKey={setActiveKey}
                searchRef={searchRef}
                carMap={carListMap}
                activeKey={activeKey}>
            </StatusRecords>,
        [activeKey, carListMap]
    )
    {/* 未发布列表 */ }
    const domUnpublishedService = React.useMemo(
        () =>
            <UnpublishedService
                activeKey={activeKey}
                // 分页
                pagination={unpublishPagination}
                // 车型车系ｍａｐ
                carMap={carListMap}
                // 服务列表数据
                dataSource={unpublishDataSource}>
            </UnpublishedService>,
        [activeKey, carListMap, unpublishPagination, unpublishDataSource]
    )
    {/* 已发布列表 */ }
    const domPublishedService = React.useMemo(
        () =>
            <PublishedService activeKey={activeKey}
                // 分页
                pagination={publishedPagination}
                // 车型车系ｍａｐ
                carMap={carListMap}
                // 服务列表数据
                dataSource={publishedDataSource}>
            </PublishedService>,
        [activeKey, carListMap, publishedPagination, publishedDataSource]
    )
    {/*  导入弹框 */ }
    const domInportFile = React.useMemo(
        () => <InportFile
            ref={importRef}
            carListCascader={searchRef?.current?.seriesModelList || []}
            showModal={isModalVisible}
            setShowModal={setIsModalVisible}
            btnLoading={importBtnLoading}
            submitModal={importWinSubmit}
            btnModalShow={checkShow}
            setBtnModalShow={(btnModalShow = false) => {
                setLocalStorage('uploadStatus', 'failed')
                setCheckShow(btnModalShow);
            }}
            btnsText={btnsText}
            titleModal={'请选择车系车型和服务矩阵版本号'}>
        </InportFile>,
        [isModalVisible, importBtnLoading, checkShow, btnsText, importWinSubmit]
    )
    {/* 退回弹窗 */ }
    const domBtnModal = React.useMemo(
        () => <BtnModal
            btnModalShow={returnShow}
            btnsText={btnsText}
            cDisabled={cDisabled}
            submitModal={noticeWinSubmit}
            setBtnModalShow={setReturnShow}>
        </BtnModal>,
        [returnShow, btnsText, cDisabled, noticeWinSubmit]
    )

    useUnmount(() => {
        initLocalStorage()
    })

    useMount(() => {
        initLocalStorage()
    })

    React.useEffect(() => {
        if (modalTask == 'returnModal' && textAreaReason.length < 5) {
            setCDisabled(true)
        } else {
            setCDisabled(false)
        }
    }, [modalTask, textAreaReason.length])
    return (
        <div className={styles.ServiceManage}>
            <CustomSpin spinning={loading}>
                {domPageTabs}
                {domSearchForm}
                <div
                    style={{
                        backgroundColor: '#fff',
                        padding: '10px 20px',
                        marginTop: '10px'
                    }}>
                    {domStatusRecords}
                    {domUnpublishedService}
                    {domPublishedService}
                </div>
            </CustomSpin>
            {domInportFile}
            {domBtnModal}
            {/* 全局任务组件 */}
            <RequestSequence />
        </div>
    )
}

export default connect(({ serviceModel, menu, loading, task }: { serviceModel: any; menu: any; loading: any; task: any }) => ({
    serviceModel,
    menu,
    loading: loading.models.serviceModel,
    task
}))(serviceManage);